package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @package com.leyou.user.interceptors
 * @description: 访问权限拦截器
 * @author: 许超越
 * @date 2019/7/10 14:39
 * @version: V1.0
 */
@Slf4j
public class PrivilegeInterceptor implements HandlerInterceptor {

    private JwtProperties prop;


    public PrivilegeInterceptor(JwtProperties prop) {
        this.prop = prop;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //获取token
            String token = request.getHeader(prop.getAppTokenProperties().getHeaderName());
            //获取载荷
            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), AppInfo.class);
            //获取用户信息
            AppInfo appInfo = payload.getUserInfo();
            //本服务的访问权限
            List<Long> targetList = appInfo.getTargetList();
            //获取本服务的id
            Long id = prop.getAppTokenProperties().getId();
            //判断是否具备访问权限
            if (targetList == null || !targetList.contains(id)) {
                //说明没有访问权限
                throw new RuntimeException("请求者没有访问本服务的权限！");
            }
            log.info("服务{}正在请求资源:{}", appInfo.getServiceName(), request.getRequestURI());
            return true;
        } catch (RuntimeException e) {
            log.error("服务访问被拒绝,token认证失败!", e);
            return false;
        }
    }
}
